/**
 * Copyright (C) 2008 GeoScheduler Team, as stated on <http://www.geoscheduler.org/authors>.
 * 
 * This file is part of GeoScheduler.
 * 
 * GeoScheduler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GeoScheduler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with GeoScheduler. If not, see <http://www.gnu.org/licenses/>.
 */

package org.geoscheduler.commons.marshaller;

import java.util.Iterator;

import org.geoscheduler.commons.collections.TransformingIterator;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * 
 * <h2>MarshallingIterator</h2>
 * <p>
 * Iterator for marshalling {@link Iterable} objects. Instances can be before
 * marshalling modified implementing {@link ItemCallback} interface.
 * {@link ItemCallback#onItem} function is called before passing object to
 * marshaller.
 * </p>
 * 
 * @author LKo (Lukas.Kolisko@Geoscheduler.Org)
 */
public class MarshallingIterator<F> extends TransformingIterator<F, JSONObject> {

	public interface ItemCallback<F> {
		public Object onItem(F item);
	}

	public static ItemCallback<Object> VOID_ITEM_CALLBACK = new ItemCallback<Object>() {
		public Object onItem(Object item) {
			return item;
		}
	};

	private final JSONMarshaller marshaller;
	private final ItemCallback<F> callback;

	public MarshallingIterator(Iterator<F> inner, JSONMarshaller marshaller) {
		this(inner, marshaller, (ItemCallback<F>) VOID_ITEM_CALLBACK);
	}

	public MarshallingIterator(Iterator<F> inner, JSONMarshaller marshaller, ItemCallback<F> callback) {
		super(inner);
		this.marshaller = marshaller;
		this.callback = callback;
	}

	@Override
	protected JSONObject next(F origin) {
		try {
			return marshaller.marshall(callback.onItem(origin), new JSONObject());
		} catch (JSONException ex) {
			throw new IllegalStateException("failed to marshall item " + origin, ex);
		}
	}

}
